package com.oceansoft.mobile.biz.api.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.coobird.thumbnailator.Thumbnails;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import sun.misc.BASE64Decoder;

import com.oceansoft.mobile.biz.api.entity.Lawyer;
import com.oceansoft.mobile.biz.api.entity.LawyerRecord;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.biz.api.service.IApiLawyerRecordService;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.Base64Utils;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.UuidUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;
/**
 * 
 * @author 律师备案
 * 
 */
@Controller
@RequestMapping("api/lawyerRecord")
public class ApiLawyerRecordController {
  
	// private static final String host="http://221.224.13.5:8190/econsole";

	@Resource
	private IApiLawyerRecordService lawyerRecordService;

	@RequestMapping(value = "gotopage/{pageName}")
	public String gotoMattersPage(@PathVariable("pageName") String pageName,HttpSession session,HttpServletRequest request,Model model) {
		String source = (String) request.getSession().getAttribute("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/lawyerRecord/" + pageName;
	}
	/**
	 * 所有url进入 判断登录
	 * @param state
	 * @param request
	 * @param model
	 * @param session
	 * @return
	 */
	 @RequestMapping(value = "gotoPageByUserAll/{state}", method = RequestMethod.GET)
	    public String gotoPages(@PathVariable("state") String state,
	                            HttpServletRequest request, Model model, HttpSession session) {
	        model.addAttribute("openId", (String) request.getSession().getAttribute("openId"));
	        model.addAttribute("state", state);
	        //System.out.println(request.getSession().getAttribute("openId"));
	        //获取重定向的url
	        String url =  Constant.stateMap.get(state);
	        if(StringUtils.isEmpty(url))
	        {
	        	url =  Constant.stateMap.get("0");
	        }
	        model.addAttribute("url",url);
	        Member member = (Member) session.getAttribute(Constant.SESSION_USER);
	        model.addAttribute("data", member);
	        String source = (String) request.getSession().getAttribute("source");
	        if (!StringUtils.isEmpty(source)) {
	        	//model.addAttribute("source", source);
	        	if(url.indexOf("?")>=0)
	        	{
	        		url+="&source="+source;
	        	}
	        	else
	        	{
	        		url+="?source="+source;
	        	}
	        	
	        }
	        return "redirect:"+url;
	        
	    }
	/**
	 * 新增一个需要登录的跳转控制
	 *
	 * @return
	 */
	@RequestMapping(value = "gotopageWithUser/{pageName}")
	public String gotoMattersPageWithUser(@PathVariable("pageName") String pageName,HttpServletRequest request,Model model) throws IllegalArgumentException, IOException {
		//判断用户是否登录
		boolean b = WeixinUtil.checkIsLoginUser(request);
		HttpSession session = request.getSession();
		String source = (String) session.getAttribute("source");
		 if (!StringUtils.isEmpty(source)) {
		       	model.addAttribute("source", source);
		       }
		if(!b){//未登录
			model.addAttribute("openId", (String) request.getSession().getAttribute("openId"));
			model.addAttribute("gotoPage","/api/lawyerRecord/gotopageWithUser/"+pageName);
			return "weixin/login/login";
		}else{//已登录			
			Member member = (Member)session.getAttribute(Constant.SESSION_USER);
			model.addAttribute("data",member);
			//根据登录用户的guid获取律师信息 (没有图片信息！！！)
			Lawyer law = lawyerRecordService.queryLawByOpenId(member.getGuid());
			if(law != null ){//律师信息不为空
				session.setAttribute(Constant.SESSION_LAWYER, law);
				model.addAttribute("lawyer", law);
			}
		    return "weixin/lawyerRecord/" + pageName;
		}
	}
	
	/**
	 * 下载文件
	 * 
	 * @param request
	 * @param response
	 * @param flag
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="downloadImg/{flag}")
	public Result download(HttpServletRequest request,HttpServletResponse response,
			@PathVariable("flag")String flag){
		
		try {
			HttpSession session = request.getSession();
			Lawyer law =(Lawyer) session.getAttribute(Constant.SESSION_LAWYER);//这个方法无图片信息
			Lawyer lawyer = lawyerRecordService.queryLawByOpenId2(law.getOpenid());//这个方法有图片信息
			
			String fileName="";//文件名
			String file = "";//下载的文件
			if("1".equals(flag)){//
				fileName = "律师执业证书（发证机关页）.jpg";
				file = lawyer.getZyzjgImg();
				
			}else if("2".equals(flag)){
				fileName = "律师执业证书（最新年度考核页）.jpg";
				file = lawyer.getZyzkhImg();
				
			}else if("3".equals(flag)){
				fileName = "律师事务所证明.jpg";
				file = lawyer.getSwsImg();
				
			}else if("4".equals(flag)){
				fileName = "委托书或法律援助公函.jpg";
				file = lawyer.getWtsImg();
				
			}
			BASE64Decoder decoder = new BASE64Decoder();//解码
			byte[] bytes = decoder.decodeBuffer(file);//将字符串转换为byte数组
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
			
			OutputStream os = new BufferedOutputStream(response.getOutputStream());
		    response.setContentType("application/octet-stream");
		    
		    int byteread = 0;
			byte[] b = new byte[1024];
			while ((byteread = in.read(b)) != -1) {
				os.write(b, 0, byteread); //文件写操作
            }
		    os.flush();
		    os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Result("下载成功");
	}
	/**
	 * 查看图片
	 * @param request
	 * @param response
	 * @param flag
	 * @param model
	 * @return
	 */
	@RequestMapping(value="showImg/{flag}")
	public String showImg(HttpServletRequest request,HttpServletResponse response,
			@PathVariable("flag")String flag,Model model){
		
		try {
			HttpSession session = request.getSession();
			Lawyer law =(Lawyer) session.getAttribute(Constant.SESSION_LAWYER);//这个方法无图片信息
			Lawyer lawyer = lawyerRecordService.queryLawByOpenId2(law.getOpenid());//这个方法有图片信息
			
			String fileName="";//文件名
			String file = "";//下载的文件
			if("1".equals(flag)){//
				fileName = "律师执业证书（发证机关页）";
				file = lawyer.getZyzjgImg();
				
			}else if("2".equals(flag)){
				fileName = "律师执业证书（最新年度考核页）";
				file = lawyer.getZyzkhImg();
				
			}else if("3".equals(flag)){
				fileName = "律师事务所证明";
				file = lawyer.getSwsImg();
				
			}else if("4".equals(flag)){
				fileName = "委托书或法律援助公函";
				file = lawyer.getWtsImg();
			}
			model.addAttribute("fileName", fileName);
			model.addAttribute("file", file);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "weixin/lawyerRecord/showImg";
	}
	
	/**
	 * 添加律师信息
	 * 
	 * @param lawyer
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "sLawyer")
	public ModelMap saveLawyer(Lawyer lawyer, HttpServletRequest request, ModelMap model) {
		try {
			
			HttpSession session = request.getSession();
			Member member =(Member)session.getAttribute(Constant.SESSION_USER);
			lawyer.setOpenid(member.getGuid());//当前用户唯一标识
			
			Lawyer law = lawyerRecordService.queryLawByOpenId(lawyer.getOpenid());
			if(law != null){//数据已经存在
				model.put("code", 1001);
			}else{
				lawyerRecordService.saveLawyer(lawyer, request);
				model.put("code", 1000);
			}
			String source = (String) request.getSession().getAttribute("source");
		    if (!StringUtils.isEmpty(source)) {
		       	model.addAttribute("source", source);
		    }
	        
		} catch (Exception e) {
			e.printStackTrace();
			model.put("code", 9000);
		}
		return model;
	}
	/**
	 * 编辑律师信息
	 * 
	 * @param lawyer
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "eLawyer")
	public ModelMap editLawyer(Lawyer lawyer, HttpServletRequest request, ModelMap model) {
		try {
			
			lawyerRecordService.updateLawyer(lawyer, request);
			model.put("code", 1000);
			
			String source = (String) request.getSession().getAttribute("source");
			if (!StringUtils.isEmpty(source)) {
				model.addAttribute("source", source);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			model.put("code", 9000);
		}
		return model;
	}
	/**
	 * 新增备案信息
	 * 
	 * @param lawyer
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "sRecord")
	public ModelMap saveRecord(LawyerRecord record, HttpServletRequest request, ModelMap model) {
      try {
			//根据接警编号和用户标示查询
    	    LawyerRecord lawyerRecord = lawyerRecordService.queryRecord(record);
    	    
    	    if(null != lawyerRecord){//数据已经存在
    	    	model.put("code", 1001);
    	    }else{
    	    	lawyerRecordService.saveRecord(record, request);
    	    	model.put("code", 1000);
    	    }
			String source = (String) request.getSession().getAttribute("source");
		    if (!StringUtils.isEmpty(source)) {
		       	model.addAttribute("source", source);
		    }
	        
		} catch (Exception e) {
			e.printStackTrace();
			model.put("code", 9000);
		}
      return model;
	}
	
	/**
	 * 查询律师备案记录
	 * 
	 * @param request
	 * @param xyrName
	 * @param xyrCard
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "queryRecord")
	public String queryRecord(HttpServletRequest request,Model model,
			@RequestParam(value="xyrName",required=false)String xyrName,
			@RequestParam(value="xyrCard",required=false)String xyrCard,
			@RequestParam(value="beginTime",required=false)String beginTime,
			@RequestParam(value="endTime",required=false)String endTime){
		try {
			
			List<LawyerRecord> recordlist = lawyerRecordService.queryRecordList(xyrName,xyrCard,beginTime,endTime,request);
			model.addAttribute("recordlist", recordlist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "weixin/lawyerRecord/recordList";
	}
	/**
	 * 查询一个月内律师对某个嫌疑人的备案记录
	 * 
	 * @param request
	 * @param model
	 * @param xyrName 嫌疑人姓名
	 * @param xyrCard 嫌疑人身份证号
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryRecordByCord")
	public Model queryRecordBy(HttpServletRequest request,Model model,
			@RequestParam(value="xyrName")String xyrName,
			@RequestParam(value="xyrCard")String xyrCard){
		try {
			//一个月以内的
			Calendar c = Calendar.getInstance();
			c.add(Calendar.MONTH, -1);
			SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
//			lawyerRecordService.queryRecordByCard(xyrName,xyrCard);
			List<LawyerRecord> recordlist = lawyerRecordService.queryRecordList(xyrName,xyrCard,s.format(c.getTime()),"",request);
			
			model.addAttribute("recordlist", recordlist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}

}
